<template>
  <view class="container">
    <view class="input-container">
      <view v-for="index in 4" :key="index" class="verify-input">
        <input
          type="number"
          class="input-field"
		  v-model="values[index-1]"
          :maxlength="1"
          :focus="focusIndex === index - 1"
          @input="handleInput(index - 1, $event)"
		  @keydown.delete="handleDelete(index - 1, $event)"
          @focus="handleFocus(index - 1,$event)"
        />
      </view>
    </view>
  </view>
</template>

<script>

export default{
	data(){
		return {
			focusIndex:0,
			values:['', '', '', ''],
		}
	},
	onMounted(){
	  // 初始化焦点
	  nextTick(() => {
	     const firstInput = this.$refs.input.value[0]
	     firstInput?.focus()
	  })
	},
	methods:{
		handleDelete(index,event){
			// 如果输入值为空，则聚焦前一个输入框
			if (index > 0) {
			  this.focusIndex = index - 1
			  this.values[index] = ''
			}else{
			  this.values[index] = ''
			}
		},
		/**
		 * 处理每个输入值函数
		 * @param index - 序号.
		 * @param event - 输入事件对象.
		 */
		handleInput (index, event) {
		  // 获取输入框的值
		  const input = event.target
		  const value = input.value
		
		  if (value) {
		    // 更新输入值数组
		    this.values[index] = value
		
		    // 判断是否还有下一个输入框，如果有则聚焦
		    if (index < 3) {
				this.focusIndex = index + 1
		    }
		
		    // 判断是否所有输入框都已经有值，如果有则触发完成事件
		    if (this.values.every((v) => v.length > 0)) {
		      this.handleComplete()
		    }
		  } else {
		    // 如果输入值为空，则聚焦前一个输入框
		    if (index > 0) {
		      this.focusIndex = index - 1
		      this.values[index] = ''
		    }
		  }
		}
		
		// 处理焦点事件
		, handleFocus(index,event) {
		  this.focusIndex = index
		}
		
		// 处理完成事件
		, handleComplete(){
		  const code = this.values.join('')
		  console.log('验证码输入完成:', code)
		},
		
	}
}




</script>

<style>
.input-container {
  display: flex;
  justify-content: space-between;
}

.verify-input {
  width: 60px;
  height: 60px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.input-field {
  width: 100%;
  height: 100%;
  text-align: center;
  font-size: 24px;
  border: none;
  border-bottom: 2px solid #ccc;
  outline: none;
}
</style>
